    export default {
        name: "bgsxMain",
        setup(props, { emit }) {
            const { smartSpeak } = inject('speech'); //语音
            const title = ref('新建查询');
            const dialogBgsx =ref(false);
            const tableData = ref([]);
            const total = ref(0);
        	const newbgsx = ref({formname: '', cxtj: '', glcx: '', kfcx: [], kftb: [], beizhu:'', fields: {}});
            const pagesys = ref({page: 1, pageSize: 16, search: ''});
            const xmlist = ref([]); //多表联查项目列表
            const mblist = ref([]); //页面模板
		    const zsmblist = ref([]); //证书模板
		    const bgsx = ref({});
		    const tbyoptions = ref([]);
		    const shyoptions = ref([]);
		    const user = JSON.parse(localStorage.getItem('user')) || {};
		    const selectedRows = ref([]); // 存储选中的行
            
            onMounted(() => {
                getData();
                gettemplates(); //获取页面模板列表
				getzsmbdata(); //获取证书模板列表
                getbgsxlist(); //获取多表联查项目列表
                gettbyuser();
            });
            
            const isadmin = computed(() => {
                return ['admin', 'xmgly'].includes(user.Role);
            })
            
            const getData = async () => {
				const res = await getbgsxlistapi(pagesys.value);
				tableData.value = res.items;
				total.value = res.total;
			};
			
			//获取项目管理员、填报员和审核员id=>name列表
			const gettbyuser = async () => {
			    const res = await getformusers();
			    if(res) {
                    tbyoptions.value = res.filter(user => ['xmgly','tby'].includes(user.role)).map(user => ({ label: user.name, value: user.id }));
                    shyoptions.value = res.filter(user => user.role == 'shy').map(user => ({ label: user.name, value: user.id }));
			    }
			}
			
			//获取多表联查项目列表
			const getbgsxlist = async () => {
			    const res = await getbgsxlistapi({page: 1, pageSize: 100});
				if(res.total > 0){
					xmlist.value = [];
					res.items.forEach(item=>{
						if(item.id != newbgsx.value.id && !item.dblc) xmlist.value.push({label: item.formname, value: item.id});
					})
				}
			};
			
            //获取页面模板列表
			const gettemplates = async() => {
				const res = await gettemplatelist({page: 1, pageSize: 100});
				if(res.total > 0){
					mblist.value = [];
					res.items.forEach(item=>{
						mblist.value.push({label: item.name, value: item.id});
					})
				}
			};
			
			//获取证书模板列表
			const getzsmbdata = async() => {
				const res = await getpictemplist({page: 1, pageSize: 100});
				if(res.total > 0){
					zsmblist.value = [];
					res.items.forEach(item=>{
						zsmblist.value.push({label: item.name, value: item.id});
					})
				}
			};
            
            //每页条数改变时触发 选择一页显示多少行
            const handleSizeChange = (val) => {
                pagesys.value.page = 1;
                pagesys.value.pageSize = val;
                getData();
            };
        
            //翻页
            const handleCurrentChange = (val) => {
                pagesys.value.page = val;
                getData();
            };
        
            //每页数量改变
            const sizechange = (e) => {
                pagesys.value.pageSize = e;
                getData();
            };
        	
            //新建查询
        	const addbgsxform = () => {
        	    title.value = '新建查询';
        	    newbgsx.value = {formname: '', cxtj: '', glcx: '', kfcx: [], beizhu:'', fields: {}};
        	    dialogBgsx.value = true;
        	};
        	
        	//修改查询
        	const editbgsxform = (row) => {
        	    title.value = '修改查询';
        	    newbgsx.value = {...row};
        	    dialogBgsx.value = true;
        	};
        	
        	//删除查询
        	const handleDelete = _.debounce(async (row) => {
        	    if(!row.tablename || !row['id']) return ElMessage.error('数据不存在');
                try {
                    await ElMessageBox.confirm(' 您确定要删除这个查询吗？', '删除确认', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }); 
                    await delbgsxapi({ ids: [row.id] });
                    getData();
                } catch (error) {
                    if (error === 'cancel') {
                        return;  // 用户点击了取消，不进行处理
                    }
                    console.error('删除失败:', error);
                    ElMessage.error('删除失败，请稍后再试');
                    smartSpeak('删除失败');
                }
        	}, 300);
            
            // 接收子组件的状态更新
            const handleDialogUpdate = (newValue) => {
                dialogBgsx.value = newValue;
            };
            
            // 查看表数据
            const handleView = (row) => {
                if(row.id) router.push({ name: 'AdminTable', query: { id: row.id } });
            }
            
            const currentQrValue = ref('');
            const qrDialogVisible = ref(false);
            const showQrDialog = (row) => {
                if (!row.id) return;
                if (row.cxtj.length == 0 && row.kftb?.length) {
                    currentQrValue.value = `${window.APP_CONFIG.baseurl}#/subpages/index/tb?tableid=${row.id}&cjz=${user.ID}&rowid=0&data=%257B%257D`;
                }else if (!row.glcx) {
                    currentQrValue.value = `${window.APP_CONFIG.baseurl}#/subpages/index/cxtj?id=${row.id}&cjz=${user.ID}`;
                }else{
                    return;
                }
                bgsx.value = row;
                qrDialogVisible.value = true;
            }
            
            const isviewewm = (row) => {
                return row.id && (row.cxtj.length > 0 || row.kftb?.length) && !row.glcx;
            }
            
            const copyCode = async (text) => {
                try {
                    await navigator.clipboard.writeText(text);
                    ElMessage.success('已复制链接');
                } catch (err) {
                    ElMessage.error('复制失败，请手动复制');
                }
            }
            
            //系统清理，无用的表
            const cleansys = _.debounce(async () => {
                try {
                    await ElMessageBox.confirm(' 确定要清理无用的数据表吗？', '清理确认', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }); 
                    await cleanapi();
                    ElMessage.success('清理完成');
                    getData();
                } catch (error) {
                    if (error === 'cancel') {
                        return;  // 用户点击了取消，不进行处理
                    }
                    console.error('清理失败:', error);
                    ElMessage.error('清理失败，请稍后再试');
                    smartSpeak('清理失败');
                }
            },500);
            
            // 选择行数据
    		const handleSelectionChange = (rows) => {
    		    selectedRows.value = rows;
    		}
    		
            // 导出项目设置
            const dcbgsx = () => {
                if (!selectedRows.value?.length) {
                    smartSpeak('请选择要导出的项目');
                    return ElMessage.error('请选择要导出的项目');
                }
                try {
                    // 1. 转换为格式化JSON字符串
                    const jsonString = JSON.stringify(selectedRows.value, null, 2);
                    // 2. 创建Blob对象
                    const blob = new Blob([jsonString], { type: 'application/json' });
                    // 3. 创建下载链接
                    const url = URL.createObjectURL(blob);
                    // 4. 创建虚拟链接元素
                    const a = document.createElement('a');
                    a.href = url;
                    // 生成带时间戳的文件名（替换非法字符）
                    const fileName = `export_${new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_')}.json`;
                    a.download = fileName;
                    // 5. 触发下载
                    document.body.appendChild(a);
                    a.click();
                    // 6. 清理资源
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                } catch (error) {
                    console.error('导出失败:', error);
                    ElMessage.error('导出失败，请检查数据格式');
                }
            }
            
            return {
                cleansys,
                isadmin,
                user,
                bgsx,
                gettbyuser,
                tbyoptions,
                shyoptions,
                copyCode,
                isviewewm,
                qrDialogVisible,
                currentQrValue,
                showQrDialog,
                handleView,
                handleDelete,
                tableData,
                dialogBgsx,
                getData,
                title,
                total,
                addbgsxform,
                pagesys,
                handleSizeChange,
                handleCurrentChange,
                sizechange,
                newbgsx,
                editbgsxform,
                xmlist,
                mblist,
                zsmblist,
                getbgsxlist,
                gettemplates,
                getzsmbdata,
                handleDialogUpdate,
                handleSelectionChange, dcbgsx,
            };
        },
        
        template: `
            <div>
               <el-dialog v-model="qrDialogVisible" width="500px">
                    <div style="display: grid;grid-template-rows: auto auto;justify-items: center;row-gap: 20px;">
                        <div><h2>手机扫码查看</h2></div>
                        <qrcode-vue :value="currentQrValue" :size="300"/>
                        <div style="line-height:1.5em;text-align:center;">
                            <div style="margin:0 0 10px 0;">
                                <h3>{{bgsx.formname}}</h3>
                                <span style="font-size:13px;color:#bcbcbc">{{user.Name}}</span>
                            </div>
                            <div>
                                <el-button type="success" @click="copyCode(currentQrValue)">复制链接</el-button>
                            </div>
                        </div>
                    </div>
                </el-dialog>
                
                <el-dialog v-model="dialogBgsx" :title="title" width="70%">
                    <readxlsx v-if="title == '新建查询'" :tbyoptions="tbyoptions" @update:dialog-visible="handleDialogUpdate" @update-success="getData"></readxlsx>
                    <bgsxform v-else :key="newbgsx.id" :form-data="newbgsx" @update:dialog-visible="handleDialogUpdate" @update-success="getData" :xmlist="xmlist" :mblist="mblist" :zsmblist="zsmblist" :tbyoptions="tbyoptions" :shyoptions="shyoptions"></bgsxform>
            	</el-dialog>
            	
                <div style="padding:3px 0 15px 0;font-size:14px;">项目三种状态：1.仅查询：有查询条件无开放填报；2.仅填报：无查询条件有开放填报；3.先查后改：有查询条件有开放填报。</div>
                <div style="display: flex; align-items: center;">
                    <el-button type="primary" @click="addbgsxform()">新建查询</el-button>
                    <el-button type="primary" @click="dcbgsx()">导出项目设置</el-button>
                    <el-button type="danger" @click="cleansys()">系统清理</el-button>
                    <el-input style="width:500px;margin-left: 10px;" v-model="pagesys.search" placeholder="输入关键词查找项目" clearable @keyup.enter="getData" @clear="getData">
                        <template #prefix>
                        	<el-icon class="el-input__icon"><search /></el-icon>
                        </template>
    					<template #append>
                            <el-button @click="getData">搜索</el-button>
                        </template>
    				</el-input>
                </div>
            
                <el-table class="mt-1" :data="tableData" table-layout="auto" :header-cell-style="{'font-size': '14px', background: '#f9f9f9'}" border show-overflow-tooltip :row-key="(row) => row.id" v-if="total > 0"  @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
                    <el-table-column prop="formname" label="查询名称" :min-width="300">
                        <template #default="scope">
                            <span v-if="!scope.row.dblc" @click="handleView(scope.row)">{{scope.row.formname}}</span>
                            <span v-else style="color:blue">{{scope.row.formname}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="starttime" label="开始时间" :width="170">
                        <template #default="scope">
                            <span>{{ scope.row.starttime ? $validators.formatDate(scope.row.starttime) : '' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="endtime" label="结束时间" :width="170">
                        <template #default="scope">
                            <span>{{ scope.row.endtime ? $validators.formatDate(scope.row.endtime) : '' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="cxtj" label="类型" :width="60">
                        <template #default="scope">
                            <span v-if="scope.row.cxtj?.length && !scope.row.glcx">查询</span>
                            <span style="color:blue" v-else-if="scope.row.kftb?.length">填报</span>
                            <span style="color:red" v-else-if="scope.row.cxtj?.length && scope.row.glcx">关联</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sfbt" label="必填" :width="60">
                        <template #default="scope">
                            <span style="color:red">{{ scope.row.sfbt ? '√' : ''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="mhcx" label="模糊" :width="60">
                        <template #default="scope">
                            <span style="color:red">{{ scope.row.mhcx ? '√' : ''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="glcx" label="关联" :width="60">
                        <template #default="scope">
                            <span style="color:red">{{ scope.row.glcx ? '√' : ''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dblc" label="多表" :width="60">
                        <template #default="scope">
                            <span style="color:red">{{ scope.row.dblc ? '√' : ''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="二维码" width="80">
                        <template #default="scope">
                            <template v-if="isviewewm(scope.row)">
                                <el-button link @click="showQrDialog(scope.row)">查看</el-button>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="CreatedAt" label="创建时间" :width="170">
                        <template #default="scope">
                            <span>{{ $validators.formatDate(scope.row.CreatedAt)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" :width="170">
                        <template #default="scope">
                        <el-button link type="success" v-if="!scope.row.dblc" @click="handleView(scope.row)">查看</el-button>
                        <el-button link type="primary" @click="editbgsxform(scope.row)" v-if="isadmin">修改</el-button>
                        <el-button link type="danger" @click="handleDelete(scope.row)" v-if="isadmin">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            	<el-pagination v-if="tableData?.length > 0" background @size-change="sizechange" :page-sizes="[10, 20, 30, 50]" :page-size="pagesys.pageSize" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" :total="total" :current-page.sync="pagesys.page"></el-pagination>
            </div>
        `
    }